package com.fengye.validation.config;

import org.springframework.context.support.AbstractMessageSource;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Locale;

@Component
public class DatabaseMessageSource extends AbstractMessageSource {

    private final MessageRepository messageRepository;

    public DatabaseMessageSource(MessageRepository messageRepository) {
        this.messageRepository = messageRepository;
    }

    @Override
    protected MessageFormat resolveCode(String code, Locale locale) {
        String message = getMessageFromDatabase(code, locale);
        if (message != null) {
            return new MessageFormat(message, locale);
        }
        return null;
    }


    private String getMessageFromDatabase(String code, Locale locale) {
        // 在这里执行数据库查询以获取消息
        // 这里使用伪代码，实际上需要使用 JPA 或其他持久化机制
        return messageRepository.getMessage(code, locale.toString());
    }
}
